'use strict';

/* Chart.js docs: https://www.chartjs.org/ */

window.chartColors = {
    green: '#75c181',
    gray: '#a9b5c9',
    text: '#252930',
    border: '#e7e9ed'
};

/* Random number generator for demo purpose */
var randomDataPoint = function () {
    return Math.round(Math.random() * 10000)
};

function parseDate(date) {
    return (date.getMonth() + 1) + '/' + date.getDate()
}

function diffDay(lastDate, earlyDate) {
    return (Date.parse(lastDate) - Date.parse(earlyDate)) / 1000 / 60 / 60 / 24;
}

let orders = []
window.addEventListener('load', () => {
    $.ajax({
        url: '/ms/api/orders',
        method: 'get',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        success: function (result) {
            if (result == null) return
            for (let i in result) {
                var order = {}
                order['time'] = new Date(result[i]['time'])
                order['money'] = result[i]['count'] * result[i]['price']
                orders.push(order)
            }
            loadChart('近7天')
        }
    })
})

function loadChart(mode) {
    var container = document.getElementById('canvas-container')
    container.innerHTML = ''
    var chart = document.createElement('canvas')
    chart.className = 'chartjs-render-monitor'
    chart.width = 673
    chart.height = 448
    chart.style.width = '539px'
    chart.style.height = '359px'
    chart.style.display = 'block'

    let days = []
    let values = []
    let gap = 1
    if (mode === '近7天') gap = 1
    else if (mode === '近30天') gap = 5
    else if (mode === '近90天') gap = 15

    for (let i = 0; i < 7; ++i) {
        let date = new Date();
        date.setHours(0)
        date.setDate(date.getDate() - i * gap)
        days.push(date)
    }
    days.reverse()
    for (let i in days) {
        let now = days[i]
        values[i] = 0
        for (let j in orders) {
            let next = orders[j]['time']
            let day = diffDay(next, now)
            if (day > gap) break
            if (day > 0) values[i] += orders[j]['money']
        }
    }
    let labels = days
    for (let i in labels) labels[i] = parseDate(labels[i])

    var lineChartConfig = {
        type: 'line',
        data: {
            labels: labels,
            datasets: [{
                label: mode,
                fill: false,
                backgroundColor: window.chartColors.green,
                borderColor: window.chartColors.green,
                data: values,
            }]
        },
        options: {
            responsive: true,
            aspectRatio: 1.5,
            legend: {
                display: true,
                position: 'bottom',
                align: 'end',
            },
            tooltips: {
                mode: 'index',
                intersect: false,
                titleMarginBottom: 10,
                bodySpacing: 10,
                xPadding: 16,
                yPadding: 16,
                borderColor: window.chartColors.border,
                borderWidth: 1,
                backgroundColor: '#fff',
                bodyFontColor: window.chartColors.text,
                titleFontColor: window.chartColors.text,
                callbacks: {
                    label: function (tooltipItem, data) {
                        return tooltipItem.value + '元';
                    }
                },
            },
            hover: {
                mode: 'nearest',
                intersect: true
            },
            scales: {
                xAxes: [{
                    display: true,
                    gridLines: {
                        drawBorder: false,
                        color: window.chartColors.border,
                    },
                    scaleLabel: {
                        display: false,

                    }
                }],
                yAxes: [{
                    display: true,
                    gridLines: {
                        drawBorder: false,
                        color: window.chartColors.border,
                    },
                    scaleLabel: {
                        display: false,
                    },
                    ticks: {
                        beginAtZero: true,
                        userCallback: function (value, index, values) {
                            return value.toLocaleString() + '元';   //Ref: https://stackoverflow.com/questions/38800226/chart-js-add-commas-to-tooltip-and-y-axis
                        }
                    },
                }]
            }
        }
    };

    chart.getContext('2d');
    container.append(chart)
    window.myLine = new Chart(chart, lineChartConfig);
}